<?php
$relPath="../../pinc/";
require_once $relPath."dpinit.php";
include_once($relPath.'dp_main.inc');

$rows_per_page = 200;

$projectid      = ArgProjectId();
$todo           = Arg("todo");
$pagenum        = Arg("pagenum", 1);
$rowsperpage    = Arg("rowsperpage", 0);
$isall          = Arg("inactive");

$username       = $User->Username();

$User->IsLoggedIn()
    or RedirectToLogin();

if(! $User->IsProjectManager()) {
    die("angang verboten.");
}

if($todo == "advance") {
    $project = new DpProject($projectid);
    $project->AdvanceRound();
    $project = null;
}

if($todo == "toggle_avail") {
    $project = new DpProject($projectid);
    $project->ToggleAvailable();
    $project = null;
}

$heading = $isall 
    ? _("All Projects for $username")
    : _("Active Projects for $username");

    dp_header($heading);

echo "
<div id='pmheader' class='center'>
<br>\n";

echo link_to_create_project('Create a new project');

echo "<br>\n";

echo "<h1>$heading</h1>";

echo $isall
    ? "
     <a href='$pm_url/projectmgr.php'>"
            ._("Show active projects")."</a>\n"
    : "
     <a href='$pm_url/projectmgr.php"
                    ."?inactive=1'>"
        ._("Show all projects")."</a>\n";
echo "
</div>  <!-- pmheader -->\n";

$tbl = new DpTable();
$tbl->AddColumn(_("<Title"), "title", "title_link");
$tbl->AddColumn(_("<Author"), "author");
$tbl->AddColumn(_("^Task"), "difficulty");
$tbl->AddColumn(_("^Pages avail-out-done<br />(bad-total)"), 
                                        null, "page_counts");
$tbl->AddColumn(_("^PM"), "project_manager", "pmlink");
$tbl->AddColumn(_("^PP"), "checkedoutby", "coblink");
$tbl->AddColumn(_("^Round"), "roundid", "round_button");
$tbl->AddColumn(_("^Avail"), null, "status_checkbox");
$tbl->AddColumn(_("^Words"), null, "words_link");
$tbl->AddColumn(_("^Files"), null, "files_link");
$tbl->AddColumn(_("^Edit"), null, "edit_link");

$sql = project_list_sql($username, $isall);
$rows = $dpdb->SqlRows($sql);
$min_row = ($pagenum - 1) * $rows_per_page;

$rptrows = array_slice($rows, $min_row, $rows_per_page, true);
$rowcount = count($rptrows);
if ( $rowcount == 0 ) {
    echo _("No projects to show.");
    theme_footer();
    exit;
}

echo results_navigator($pagenum, $rows_per_page, $rowcount, $isall);

$tbl->SetRows($rptrows);
// $tbl->SetPager("ProjPager");
$tbl->EchoTable();

echo results_navigator($pagenum, $rows_per_page, $rowcount, $isall);

echo "</div><br>\n";
theme_footer();
exit;

    // ---------------------------------------------------------

    // Present the results of the search query.

function project_list_sql($username, $isall) {
    $where = "WHERE p.username = '$username'\n"
        . ($isall 
            ? ""
            : "AND p.state LIKE '%proj_avail'\n");

    return  "SELECT
                p.projectid,
                p.nameofwork AS title,
                p.authorsname AS author,
                p.language,
                p.other_languages,
                p.difficulty,
                p.genre,
                p.state,
                p.sequence_code,
                p.username as pm,
                SUM( 
                    CASE WHEN pg.state LIKE '%".PAGE_AVAIL."'
                        THEN 1 ELSE 0 END
                ) AS pages_avail,
                SUM( 
                    CASE WHEN pg.state LIKE '%".PAGE_OUT."'
                        THEN 1 ELSE 0 END
                    ) AS pages_out,
                SUM( 
                    CASE WHEN pg.state LIKE '%".PAGE_TEMP."'
                        THEN 1 ELSE 0 END
                    ) AS pages_temp,
                SUM( 
                    CASE WHEN pg.state LIKE '%".PAGE_SAVED."'
                        THEN 1 ELSE 0 END
                    ) AS pages_saved,
                COUNT(pg.projectid) AS pages_total,
                SUM( 
                    CASE WHEN pg.state LIKE '%".PAGE_BAD."'
                        THEN 1 ELSE 0 END
                    ) AS pages_bad,
                COUNT(pg.fileid) AS pages_total,
                p.username AS project_manager,
                p.checkedoutby,
                pm.bb_id AS pm_bbid,
                CASE WHEN p.state LIKE 'P1%' THEN 1
                     WHEN p.state LIKE 'P2a%' THEN 2
                     WHEN p.state LIKE 'P2b%' THEN 3
                     WHEN p.state LIKE 'P2c%' THEN 4
                     WHEN p.state LIKE 'P3%'  THEN 5
                     WHEN p.state LIKE 'F1a%' THEN 6
                     WHEN p.state LIKE 'F1b%' THEN 7
                     WHEN p.state LIKE 'F1c%' THEN 8
                     WHEN p.state LIKE 'F2a%' THEN 9
                     WHEN p.state LIKE 'F2b%' THEN 10
                     ELSE 11
                END AS round_index,
                cob.bb_id AS cob_bbid
            FROM
                projects AS p
            LEFT JOIN
                pages AS pg ON p.projectid = pg.projectid
            LEFT JOIN
                users AS pm ON p.username = pm.username
            LEFT JOIN
                users as cob ON p.checkedoutby = cob.username
            $where
            GROUP BY
                p.projectid
            ORDER BY projectid";
}

function title_link($title, $row) {
    global $code_url;
    $url = "$code_url/project.php"
        ."?projectid={$row['projectid']}";
    return "<a href='{$url}'>{$title}</a>";
}

function page_counts($row) {
    $class = ($row['pages_bad'] > 0
                ? "class='danger'"
                : "");
    $url = url_for_page_list($row['projectid']);
            
    $fmt = "<a $class href='{$url}'>%d-%d-%d<br />(%d-%d)</a>";

    return sprintf($fmt, $row['pages_avail'],
         $row['pages_out'] + $row['pages_temp'],
         $row['pages_saved'], $row['pages_bad'],
         $row['pages_total']);
}

function pmlink($pm, $row) {
    global $Context;
    return $Context->LinkForPMToUser($pm);
}

function coblink($cob, $row) {
    global $Context;
    if(empty($cob))
        return "";
    return $Context->LinkForPMToUser($cob);
}

function words_link($row) {
    global $wc_url;
    $projectid = $row['projectid'];
    return link_to_project_words($projectid, "Words");
}

function files_link($row) {
    global $wc_url;
    $projectid = $row['projectid'];
    return link_to_project_files($projectid, "Files");
}

function edit_link($row) {
    global $pm_url;
    global $User;
    if($User->IsSiteManager() 
        || $User->IsProjectFacilitator()
        || $row['pm'] == $User->Username()) {
        return "<a target='_blank' 
                    href='$pm_url/editproject.php"
                        ."?todo=edit"
                        ."&amp;projectid={$row['projectid']}'>"
                        ._("Edit")."</a>";
    }
    else {
        return "";
    }
}
/*
function ProjPager() {
    results_navigator(PageNumber(), RowsPerPage(), RowCount());
}
*/

function results_navigator($pagenum, $rows_per_page, $rowcount, $isall) {

    // The REQUEST_URI must have at least one parameter,
    // or the response would have been just the search form

    $str = "";
    if ( $pagenum > 1 ) {
        $prevpage = $pagenum - 1;
        $url = ThisPageUrl() . "?inactive={$isall}"
                             . "&pagenum={$prevpage}";
        $str .= "<a href='$url'>"._("Previous")."</a> |\n";
    }

    $minrow = $rows_per_page * ($pagenum-1) + 1;
    $maxrow = min($rows_per_page * $pagenum, $rowcount);

    $position = sprintf(
        _("Projects %1\$d to %2\$d of %3\$d\n"),
                                $minrow, $maxrow, $rowcount);
    $str .= "
    <div class='w90 left'>
        $position
    </div>\n";

    if ( $maxrow < $rowcount) {
        $nextpage = $pagenum + 1;
        $url = ThisPageUrl() . "?inactive={$isall}"
                             . "&pagenum={$nextpage}";
        $str .= " | <a href='$url'>"._("Next")."</a>";
    }
    return $str;
}

function row_roundid($row) {
    return preg_replace("/\..*$/", "", $row['state']);
}

function row_status($row) {
    return preg_replace("/^.*\./", "", $row['state']);
}

function status_checkbox($row) {
    global $User;

    if($row['pages_saved'] > 0
        && $row['pages_saved'] == $row['pages_total']) {
        return "completed";
    }
    if($row['pm'] != $User->Username()
        && ! $User->IsSiteManager()
        && ! $User->IsProjectFacilitator()) {
        return $row['pages_avail'] > 0 ? "avail" : "";
    }
    $projectid = $row['projectid'];
    $roundid = row_roundid($row);
    $status = row_status($row);
    $state = $row['state'];
    $checked = ($status == PROJ_AVAILABLE) ? " CHECKED" : "" ;
    return "<form name='cs_$projectid' action=''
                accept-charset='UTF-8' method='POST'>
            <input type='hidden' name='projectid' value='$projectid'>
            <input type='hidden' name='todo' value='toggle_avail'>
            <input class='right' type='checkbox' name='chkavail'
            onclick='this.form.submit()' $checked>
            </form>\n";
}

function round_button($roundid, $row) {
    $projectid = $row['projectid'];
    $roundid = row_roundid($row);
    $state = $row['state'];
    if($row['pages_saved'] == 0
        || $row['pages_saved'] != $row['pages_total']) {
        return $roundid;
    }

    $seq_code = $row['sequence_code'];
    $nextroundid = RoundIdAfter($roundid, $seq_code);
    if(! $nextroundid) {
        $nextroundid = "PP";
    }
    return "<form name='frmadvanc' action='' accept-charset='UTF-8' method='POST'>
        <input type='hidden' name='projectid' value='$projectid'>
        <input type='hidden' name='todo' value='advance'>
        <input type='submit' name='submit_advance' value='$nextroundid'>
    </form>\n";
}

// -------------------------------------------------------------------
// vim: sw=4 ts=4 expandtab
?>
